/**
 * Created by bo.wang on 2022/3/1.
 */
import React, {useState} from 'react'
import {Stage, Layer} from 'react-konva'
import LabelRect from '../../components/shapes/LabelRect'
import Konva from "konva"

import styles from './Mind.module.scss'


const Mind = () => {
    const [selected, setSelected] = useState<string | null>(null)
    const [inputShape, setInputShape] = useState<React.CSSProperties>({})
    const [inputValue, setInputValue] = useState<string>("")
    const rects = [...Array(10)].map((_, index) => {
        return {
            key: index,
            x: index * 50,
            y: index * 50,
            id: `${index}`,
            text: `node-${index + 1}`,
            onClick: (layer: Konva.Container | null) => {
                setSelected(layer?.id() || null)
                let shape: React.CSSProperties = {
                    width: (layer?.children![1].attrs.text.length || 1) * 15,
                    height: (layer?.children![1].attrs.text.split("\n").length + 1 || 1) * 15,
                    top: (layer?.x() || 0) + 8,
                    left: (layer?.y() || 0) + 10,
                }
                setInputShape(shape)

                setInputValue(layer?.children![1].attrs.text)
            }
        }
    })
    const [rectList, setRectList] = useState(rects)
    const changeLabel = (text: string) => {
        let rectListBak = [...rectList]
        let inputShapeBak = {...inputShape}
        inputShapeBak.width = (text.length + 1) * 15
        inputShapeBak.height = (text.split("\n").length + 1) * 15
        rectListBak[parseInt(selected as string)].text = text
        setRectList(rectListBak)
        setInputShape(inputShapeBak)
        setInputValue(text)
    }
    return (
        <div className={styles.container}>
            <Stage width={window.innerWidth - 200} height={window.innerHeight - 200}>
                <Layer>
                    {rectList.map(item => <LabelRect {...item} selected={selected === item.id}/>)}
                </Layer>
            </Stage>
            <textarea
                className={styles.inputStyle}
                value={inputValue}
                onChange={e => changeLabel(e.target.value)}
                style={inputShape}
            />
        </div>
    )
}

export default Mind